package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelPageReqDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-16
 */
@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmNewsService wmNewsService;

    /**
     * 修改、保存
     * @param wmChannel
     */
    @Override
    public ResponseResult updateOrSave(WmChannel wmChannel) {
        //校验
        if(wmChannel == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //修改、保存
        if(wmChannel.getId() == null){
            if (saveChannel(wmChannel)) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }else {
            if (updateChannel(wmChannel)) return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_CITED);
        }
        return ResponseResult.okResult(null);
    }

    /**
     * 修改
     * @param wmChannel
     * @return  true->频道被引用  false->频道没引用，可删除
     */
    private boolean updateChannel(WmChannel wmChannel) {
        //禁用时是否被引用
        if( !checkChannel(wmChannel.getId())){
            return true;
        }
        //修改
        updateById(wmChannel);
        return false;
    }

    /**
     * 保存
     * @param wmChannel
     * @return  true->频道存在  false->频道存在，可添加
     */
    private boolean saveChannel(WmChannel wmChannel) {
        //频道名称是否重复
        if(wmChannel.getName() != null){
            List<WmChannel> list = list();
            List<String> collect = list.stream().map((e) -> e.getName()).collect(Collectors.toList());
            //
            if(collect.contains(wmChannel.getName())){
                return true;
            }
        }
        //设置参数
        wmChannel.setCreatedTime(new Date());
        save(wmChannel);
        return false;
    }

    /**
     * 频道是否被引用     true->没引用    false->有引用
     * @param id
     * @return
     */
    private Boolean checkChannel(Integer id) {
        Boolean flag = null;
//        if(id == 1){
//            flag = true;
//        }else {
//            flag = false;
//        }
        int count = wmNewsService.count(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, id));
        if(count > 0){
            return false;
        }
        return true;
    }

    /**
     * 查询频道列表
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findList(WmChannelPageReqDto dto) {
        //校验
        if(dto == null){
            throw new RuntimeException("WmChannelServiceImpl-findList-null");
        }
        dto.checkParam();

        //分页条件
        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmChannel> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(WmChannel::getCreatedTime);

        //模糊查询
        if(StringUtils.isNotBlank(dto.getName())){
            lqw.like(WmChannel::getName,dto.getName());
        }

        //状态查询条件  (前端未传状态值)
        if(dto.getStatus() != null){
            lqw.eq(WmChannel::getStatus,dto.getStatus());
        }

        //查询
        IPage<WmChannel> iPage = page(page, lqw);

        //结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }

    /**
     * 删除频道
     *
     * @param id
     */
    @Override
    public ResponseResult delChannel(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //是否被引用
        if(!checkChannel(id)){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_ACTIVE);
        }
        wmChannelMapper.deleteById(id);
        return ResponseResult.okResult(null);
    }

    /**
     * 查询所有的频道
     *
     * @return
     */
    @Override
    public ResponseResult getChannels() {
        return ResponseResult.okResult(list());
    }
}
